﻿using CommonBase;
using CommonBase.ResponseBase;
using CustomControls.PoptipCtr;
using LogProjectManager;
using MyAppProjectControl.BaseViewModels;
using MyAppProjectControl.Model;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MyAppProjectControl.ViewModels
{
    public class LogsControlViewModel : BaseViewModel
    {
        private Dictionary<int, int> CurrentItemIndex { set; get; }
        private LogFileDbModel _SelectLogFileModel;

        public LogFileDbModel SelectLogFileModel
        {
            get { return _SelectLogFileModel; }
            set { SetProperty(ref _SelectLogFileModel, value); }
        }

        private ObservableCollection<LogFileDbModel> _LogsList;

        public ObservableCollection<LogFileDbModel> LogsList
        {
            get { return _LogsList; }
            set { SetProperty(ref _LogsList, value); }
        }


        public string DeviceID { set; get; }

        public string DeviceIpAddress { set; get; }

        private DelegateCommand<int?> _PageUpdatedCommand;
        public DelegateCommand<int?> PageUpdatedCommand =>
            _PageUpdatedCommand ?? (_PageUpdatedCommand = new DelegateCommand<int?>(ExecutePageUpdatedCommand));


        private DelegateCommand _GoIndexControlCommand;
        public DelegateCommand GoIndexControlCommand =>
            _GoIndexControlCommand ?? (_GoIndexControlCommand = new DelegateCommand(GoIndexControlCommandMethod));

        private DelegateCommand _RefreshCommand;
        public DelegateCommand RefreshCommand =>
            _RefreshCommand ?? (_RefreshCommand = new DelegateCommand(RefreshCommandMethod));



        private DelegateCommand _DownLogsCommand;
        public DelegateCommand DownLogsCommand =>
            _DownLogsCommand ?? (_DownLogsCommand = new DelegateCommand(DownLogsCommandMethod));

   

        public LogsControlViewModel(IContainerExtension container) : base(container)
        {

        }
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.Count > 0)
            {
                if (navigationContext.Parameters.ContainsKey("deviceid"))
                {
                    if (navigationContext.Parameters["deviceid"] != null)
                    {
                        DeviceID = navigationContext.Parameters.GetValue<string>("deviceid");
                    }
                    if (navigationContext.Parameters["DeviceIpAddress"] != null)
                    {
                        DeviceIpAddress = navigationContext.Parameters.GetValue<string>("DeviceIpAddress");
                    }
                }

            }
            base.OnNavigatedTo(navigationContext);
        }
        public override void ExecuteLoadedCommand()
        {
            base.ExecuteLoadedCommand();
            CurrentItemIndex = new Dictionary<int, int>();
            LogsList = new ObservableCollection<LogFileDbModel>();
            GetAllCount(DeviceID);
        }

        public override void ExecuteUnLoadedCommand()
        {
            base.ExecuteUnLoadedCommand();
        }

        private void ExecutePageUpdatedCommand(int? JumpIndex)
        {
            GetCurrentPageDevice(JumpIndex.Value, PageItemsCount);
        }

        private void GoIndexControlCommandMethod()
        {
            ToTargetConfigPage(SystemResource.Nav_IndexPageView);
        }

        private void RefreshCommandMethod()
        {
            GetAllCount(DeviceID);
            GetCurrentPageDevice(1, PageItemsCount);
        }

        private void DownLogsCommandMethod()
        {
            if (SelectLogFileModel==null) 
            {
                MessageControl.Warning("请选择要操作文件!", "RootMessageTooken");
                return;
            }
            CommonStaticModel.LastCmdType = "下载日志命令";
            DownloadLogFile(SelectLogFileModel.deviceid, SelectLogFileModel.filename, SelectLogFileModel.filepath);
        }

        private async void DownloadLogFile(string _deviceid,string fileName,string FilePath)
        {
            string UploadFolderPath=AppDomain.CurrentDomain.BaseDirectory+"DownFile//Logs//"+DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
            string apiUrl = $"http://192.168.0.41:8081/api/DownloadLog?_deviceid={_deviceid}&_FileName={fileName}&_FilePath={FilePath}";
            // 创建文件夹（如果尚未存在）

            if (!Directory.Exists(UploadFolderPath))
            {
                Directory.CreateDirectory(UploadFolderPath);
            }


            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    using (FileStream fileStream = new FileStream(System.IO.Path.Combine(UploadFolderPath, fileName), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        await response.Content.CopyToAsync(fileStream);
                    }

                    Console.WriteLine("文件下载完成.");
                    if (Directory.Exists(UploadFolderPath))
                    {
                        System.Diagnostics.Process.Start(UploadFolderPath);
                    }
                    MessageControl.Warning("文件下载完成!", "RootMessageTooken");
                }
                else
                {
                    Console.WriteLine("下载失败: " + response.ReasonPhrase);
                }
            }
        }


        private void ToTargetConfigPage(string _PagName)
        {
            NavigationParameters itemParameter = new NavigationParameters();
            Application.Current?.Dispatcher.Invoke(() => {
                Region.RequestNavigate(SystemResource.Nav_MainContent, _PagName, itemParameter);
            });
        }

        private void GetCurrentPageDevice(int _inputpageCode, int _inputPageSize)
        {
            GetAllLogs(_inputpageCode, _inputPageSize);
        }



        private async void GetAllCount(string _deviceid)
        {
            try
            {

                string apiUrl = $"http://192.168.0.41:8081/api/GetAllLosCountDevice?_deviceid={_deviceid}";
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(apiUrl);

                    if (response.IsSuccessStatusCode)
                    {
                        var read = response.Content.ReadAsStringAsync();
                        read.Wait();
                        ResponseBody json = JsonConvert.DeserializeObject<ResponseBody>(read.Result);
                        if (json.Data != null)
                        {
                            PageCount = Convert.ToInt32(json.Data);
                            PageItemsCount = Limits.FirstOrDefault();
                        }
                    }
                    else
                    {
                        Console.WriteLine("下载失败: " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetAllCount", ex.Message);
            }
        }


        private async void GetAllLogs(int _inputpageCode, int _inputPageSize)
        {
            try
            {
                LogsList.Clear();
                string apiUrl = $"http://192.168.0.41:8081/api/GetCurrentPageLogs?_deviceid={this.DeviceID}&_inputpageCode={_inputpageCode}&_inputPageSize={_inputPageSize}";
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(apiUrl);

                    if (response.IsSuccessStatusCode)
                    {
                        var read = response.Content.ReadAsStringAsync();
                        read.Wait();
                        ResponseBody json = JsonConvert.DeserializeObject<ResponseBody>(read.Result);
                        if (json.Data != null)
                        {
                            List<LogFileDbModel> devList = JsonConvert.DeserializeObject<List<LogFileDbModel>>(json.Data.ToString());
                            if (devList.Count > 0)
                            {
                                int _index = 1;
                                foreach (var item in devList)
                                {
                                    item.Index = _index;
                                    item.ipaddress = this.DeviceIpAddress;
                                    LogsList.Add(item);
                                    _index++;
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("下载失败: " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetCurrentPageDevice", ex.Message);
            }
        }

    }
}
